package org.luxor.commons.redis.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.luxor.commons.redis.annotation.RedisCacheEvict;
import org.luxor.commons.redis.client.RedisObjectClient;
import org.luxor.commons.redis.component.KeyGenerator;
import org.luxor.commons.redis.component.RedisKeys;
import org.luxor.commons.redis.component.ReflectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Redis缓存驱逐AOP
 *
 * @author Mr.Yan  @date 2019/10/22
 */
@Aspect
public class CacheEvictAspect {
    private static final Logger logger = LoggerFactory.getLogger(CacheEvictAspect.class);

    private RedisObjectClient redisObjectClient;

    public void setRedisClientObject(RedisObjectClient redisObjectClient) {
        this.redisObjectClient = redisObjectClient;
    }

    /**
     * 定义缓存驱逐逻辑
     */
    @Around("@annotation(org.luxor.commons.redis.annotation.RedisCacheEvict)")
    public Object cache(ProceedingJoinPoint pjp) throws Throwable {
        //获取所有参数
        RedisCacheEvict cacheable = ReflectUtil.getMethod(pjp).getAnnotation(RedisCacheEvict.class);
        String fieldKey =  KeyGenerator.INSTANCE.getCacheEvictKeyName(pjp, cacheable);
        fieldKey = RedisKeys.buildCacheKey(fieldKey);

        // 从缓存中删除缓存的数据
        redisObjectClient.delete(fieldKey);
        logger.info("Evicting cached data from Redis( @RedisCacheEvict ). CacheKey:[{}] ", fieldKey);
        return pjp.proceed();
    }

}